package eu.nikoladichev.test.mbean;

import javax.annotation.Resource;
import javax.ejb.Remote;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.jboss.annotation.ejb.Service;
import org.jboss.logging.Logger;

@Service(objectName = SendJmsMessage.OBJECT_NAME, xmbean = "resource:META-INF/kokod-service-xmbean.xml")
@Remote(SendJmsMessageMBean.class)
public class SendJmsMessage implements SendJmsMessageMBean {
	
	InitialContext ic;
	
	@Resource(mappedName = "java:/ConnectionFactory")
	private ConnectionFactory connectionFactory;
	
	private Queue queue;
	
	public static final String OBJECT_NAME = "eu.nikoladichev:service=SendJmsMessage";
	
	private TextMessage message;

	Logger logger = Logger.getLogger(SendJmsMessage.class.getSimpleName());

	public void sendJmsMessage() {
		Connection connection;
		try {
			ic = new InitialContext();
			queue = (Queue) ic.lookup("queue/Misho");
			connection = connectionFactory.createConnection();
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			message = session.createTextMessage();
			message.setStringProperty("queue", "Misho");
			message.setLongProperty("arrivedInQueue", 0);
			message.setText("This is a test JMS Message!");
			MessageProducer producer = session.createProducer(queue);
			producer.send(message);
			logger.info("Message sent to queue " + queue.getQueueName() + "!");
			connection.close();
		} catch (JMSException e) {
			logger.warn("JMSException: " + e.getMessage());
		} catch (NamingException ne) {
			logger.warn("NamingException: " + ne.getMessage());
		}
	}
	
}
